package cn.tedu.tmall.admin.mall.handler;

import cn.tedu.tmall.common.enumerator.ServiceCode;
import cn.tedu.tmall.common.ex.ServiceException;
import cn.tedu.tmall.common.web.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    public GlobalExceptionHandler(){
        log.debug("创建全局异常处理器:GlobalExceptionHandler ");
    }

    @ExceptionHandler
    public JsonResult handleConstraintViolationException(ConstraintViolationException e){
        log.debug("全局异常处理器开始处理 ConstraintViolationException ");
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        StringBuffer message = new StringBuffer();
        constraintViolations.forEach(ex-> {
            log.error(ex.getMessage());
            message.append(ex.getMessage());
        } );
        //log.error("出现异常",e);
        //JsonResult jsonResult = new JsonResult();
        //jsonResult.setData("");
        //jsonResult.setState(40000);
        //jsonResult.setMessage(message.toString());
        //return jsonResult;
        return JsonResult.fail(ServiceCode.ERROR_BAD_REQUEST,message.toString());
    }

    @ExceptionHandler
    public JsonResult handleBindException(BindException bindException){
        log.debug("全局异常处理器开始处理BindException");
        String defaultMessage = bindException.getFieldError().getDefaultMessage();
        log.error("请求参数格式错误",bindException);
        return JsonResult.fail(ServiceCode.ERROR_BAD_REQUEST,defaultMessage);
    }


    /**
     ** 处理系统业务异常
     */
    @ExceptionHandler
    public JsonResult handleServiceException(ServiceException serviceException){
        log.debug("全局异常处理器开始处理ServiceException");
        String defaultMessage = serviceException.getMessage();
        log.error("请求参数格式错误",serviceException);
        return JsonResult.fail(ServiceCode.ERROR_UNKNOWN,defaultMessage);
    }


    @ExceptionHandler
    public JsonResult handleGlobalException(Throwable throwable){
        log.error("出现异常:",throwable);
        //[开发的同学看到了这个异常应该去排查代码看到底哪出了异常]
        String message = "网络不好,请重试...";
        return JsonResult.fail(ServiceCode.ERROR_UNKNOWN,message);
    }


}
